'use client'

import { delNote, listNote, updateNote } from "@/clientApi/task/note";
import { BookOutlined, CalendarOutlined, DoubleLeftOutlined, DownOutlined, PlusOutlined, PushpinFilled, PushpinOutlined, StarFilled, UndoOutlined } from "@ant-design/icons";
import { Divider, Dropdown, MenuProps, Space, Spin } from "antd";
import { useEffect, useState } from "react";
import EditMenuList from "./component/editMenuList";
import EditNoteView from "./component";
import useDict from "@/utils/dict";
import { globalMessage } from "@/utils/message";
import CalendarView from "./component/CalendarView";


const NoteView: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [data, setData] = useState<any>([])
  const [noteObj, setNoteObj] = useState<any>({})
  const [menuVisible, setMenuVisible] = useState(false);
  const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 });
  const [isOpenAdd, setIsOpenAdd] = useState(false);
  const [isOpenCalendar, setIsOpenCalendar] = useState(false);
  const [queryParams, setQueryParams] = useState({
    categoryId: '1',
  });

  const [noteTypeList, setNoteTypeList] = useState<MenuProps['items']>([
    {
      key: '1',
      label: '便签',
    },
    {
      key: '2',
      label: '待办',
    },
  ]);


  const loadList = () => {
    setLoading(true);
    listNote(queryParams).then((res: any) => {
      if (res?.code === 200) {
        setData(res.rows)
      }
      setLoading(false);
    })
  }
  useEffect(() => {

    loadList()

  }, [queryParams.categoryId])

  // 处理右键点击事件
  const handleContextMenu = (event: any, element: any) => {
    event.preventDefault();
    setNoteObj(element);
    // 计算菜单位置，确保不会超出屏幕边界
    const x = Math.min(event.clientX, window.innerWidth - 200);
    const y = Math.min(event.clientY, window.innerHeight - 250);

    setMenuPosition({ x, y });
    setMenuVisible(true);
  };
  const handleOnClick = () => {

    setMenuVisible(false);
  }
  // 双击事件
  const handleDoubleClick = (event: any, element: any) => {
        // 计算菜单位置，确保不会超出屏幕边界
    const x = Math.min(event.clientX, window.innerWidth - 200);
    const y = Math.min(event.clientY, window.innerHeight - 400);

    setMenuPosition({ x, y });
    setNoteObj(element);
     setMenuVisible(true);
    console.log("双击事件触发", element);
    // 这里可以添加双击后的逻辑，比如编辑便签
    // alert(`双击了便签: ${element.description}`);
  }
  // 处理菜单项点击事件
  const handleMeanClick = (item: any) => {
    console.log(`点击了菜单项: ${item.key} - ${item.label}`);
    // 根据不同的菜单项执行不同的操作
    switch (item.key) {
      case 'edit':
        setIsOpenAdd(true);
        console.log('执行编辑操作');
        break;
      case 'finish':
        const status = noteObj.status == 1 ? 0 : 1;
        updateNote({ noteId: noteObj.noteId, status }).then((res: any) => {
          if (res.code == 200) {
            globalMessage().success(res.msg)
          }
        })
        console.log('执行完成操作');
        break;
      case 'editReminder':
        console.log('执行修改提醒操作');
        break;
      case 'deleteReminder':
        console.log('执行删除提醒操作');
        break;
      case 'delete':
        console.log('执行删除操作');
        delNote(noteObj.noteId).then((res: any) => {
          if (res.code == 200) {
            globalMessage().success(res.msg)
          }
        })
        console.log('执行删除操作');
        break;
      case 'copy':
        console.log('执行复制操作');
        break;
      case 'timeline':
        console.log('执行时间轴操作');
        break;
      case 'move':
        console.log('执行移动操作');
        break;
      case 'PinToTop':
        console.log('执行置顶操作');
        const priority = noteObj.priority == 1 ? 2 : 1;
        updateNote({ noteId: noteObj.noteId, priority }).then((res: any) => {
          if (res.code == 200) {
            globalMessage().success(res.msg)
          }
        })
        break;
      // 其他菜单项的处理...
      default:
        console.log('未知操作:', item.key);
    }
    setMenuVisible(false); // 点击后关闭菜单
    loadList();
  };
  // 新增便签
  const handleAddClick = () => {
    setNoteObj({});
    setMenuVisible(false);
    setIsOpenAdd(true);
    console.log("新增敬业签");
  };
  const handleCancle = () => {
    setIsOpenAdd(false);
    setMenuVisible(false);
    setIsOpenCalendar(false);
    loadList();
  };
  const handleNoteTypeSelect = (e: any) => {
    console.log('选择的便签类型:', e.key);
    setQueryParams({ ...queryParams, categoryId: e.key });
  };
  const handleCalendarClick = () => {
    console.log("日历点击事件");
    setIsOpenCalendar(true);
  };
  return (
    <div>
      <Spin spinning={loading} >
        {/* 主页 */}
        {!isOpenAdd && !isOpenCalendar &&
          <div className=" bg-[#808080] text-amber-50 p-5 h-screen select-none overflow-y-auto" >
            <div className="flex w-full justify-between">
              <div className="flex-1 flex justify-center">
                <Dropdown
                  menu={{ items: noteTypeList, defaultSelectedKeys: [queryParams.categoryId], onClick: handleNoteTypeSelect, }} >
                  <Space>
                    {noteTypeList && noteTypeList.map((item: any) => (
                      item.key === queryParams.categoryId && <div key={item.key}>{item.label}</div>
                    ))}
                    <DownOutlined />
                  </Space>

                </Dropdown>
              </div>
              <div className="shrink-0" onClick={loadList}><UndoOutlined /></div>

            </div>
            <div className="flex justify-between pb-5">
              <div className="flex">
                <div className="pr-1">图片</div>
                <div>翟高强</div>
              </div>
              <div onClick={handleCalendarClick}><CalendarOutlined /></div>
            </div>
            <div className="flex justify-between pb-3">
              <div className="flex items-center">
                <BookOutlined />
                <div className="pl-2">{noteTypeList && noteTypeList.map((item: any) => (
                  item.key === queryParams.categoryId && <div key={item.key}>{item.label}</div>
                ))}</div>
                <div className="text-xs pl-1">{data.length}</div>
              </div>
              <div>全部</div>
            </div>
            <div onClick={handleAddClick} className=" text-center border  rounded-xl pt-1 pb-1 text-[#cfcfcf] select-none"><PlusOutlined />新增敬业签</div>
            <div className="pt-5">
              {data.map((element: any) => (
                <div
                  className={`w-full hover:bg-[#8c8a8c] p-1 rounded-xl ${element.status == 1 ? 'bg-[#8c8a8c] text-[#c4c3c4]' : ''}`}
                  key={element.noteId}
                  onDoubleClick={(e) => handleDoubleClick(e,element)}
                  onClick={handleOnClick}
                  onContextMenu={(e) => handleContextMenu(e, element)}>
                  <div className="flex justify-end text-[#c4c4c4] ">
                    <div>已超时1天</div>
                    <div className="pl-1 text-[#1dd9db]">{element.priority == 2 ? <PushpinFilled /> : ''}</div>
                  </div>
                  <div className="flex">
                    <div className="w-4 flex items-center">·</div>
                    <div className="max-h-24 overflow-y-auto [&::-webkit-scrollbar]:w-1
                [&::-webkit-scrollbar-track]:bg-transparent
                [&::-webkit-scrollbar-thumb]:bg-[#c4c4c4]
                [&::-webkit-scrollbar-thumb]:rounded-full">{element.description}</div>
                  </div>
                  <div className="flex justify-between pt-2 text-[#a5a7ac] pb-1 pl-4">
                    <div><UndoOutlined />时间</div>
                    <div className=" text-[#f5e425]"><StarFilled /></div>
                  </div>
                  <div className="h-px bg-gray-300"></div>
                </div>

              ))}
            </div>
            {/* 右键菜单 */}
            {menuVisible && (<EditMenuList onItemClick={handleMeanClick} menuPosition={menuPosition} noteObj={noteObj} />)}
          </div>}
        {/* 新增and编辑 */}
        {isOpenAdd && <EditNoteView handleCancle={handleCancle} noteId={noteObj.noteId} categoryId={queryParams.categoryId} />}
        {isOpenCalendar && <CalendarView handleCancle={handleCancle} />}
      </Spin>
    </div>

  )

}
export default NoteView;